import { format } from 'sql-formatter';

/** Theme */
export const STORAGE_THEME_KEY = '__db_gpt_theme_key';
/** Language */
export const STORAGE_LANG_KEY = '__db_gpt_lng_key';
/** Init Message */
export const STORAGE_INIT_MESSAGE_KET = '__db_gpt_im_key';
/** Flow nodes */
export const FLOW_NODES_KEY = '__db_gpt_static_flow_nodes_key';

export function formatSql(sql: string, lang?: string) {
  if (!sql) return '';
  try {
    return format(sql, { language: lang });
  } catch {
    return sql;
  }
}

export * from './constants';
export * from './storage';

const baseUrl = 'http://192.168.30.15:10081/noahX/#';
export const onRouterChange = (url: string = '/find-index') => {
  window.open(`${baseUrl}${url}`);
};

export const logoUrl = process.env.API_BASE_URL + process.env.APP_ATAVAR_URL; 

//获取地址栏上的参数
export const getParam = (name: string): string | null => {
  if (typeof window === 'undefined') return null;

  const url = window.location.href;
  name = name.replace(/[[]]/g, '\\$&');
  const regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)');
  const results = regex.exec(url);

  if (!results) return null;
  if (!results[2]) return '';

  return decodeURIComponent(results[2].replace(/\+/g, ' '));
};
/**
 * 导出文件
 * @param file 
 * @param filename
 * @param fileType 
 * @param isNowdate 
 */
export function operateFile(file, filename, fileType = '.json', isNowdate = true) {
  var nowdate = new Date().getTime();
  const fileName = filename + (isNowdate ? nowdate : '') + fileType;
  const blobObject = new Blob([file]);
  //是IE浏览器
  if (!!window.ActiveXObject || 'ActiveXObject' in window) {
    window.navigator.msSaveOrOpenBlob(blobObject, fileName)
  } else {
    //兼容火狐，谷歌
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blobObject)
    link.setAttribute('download', fileName)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(link)
  }
}
